import { Buffer } from "buffer";
export class GolombParse {
    private data: Buffer;
    private pos: number = 0;
    constructor(srcData: Buffer) {
        this.data = Buffer.alloc(0);
        this.initData(srcData);
    }
    public printNextBinary(len: number, tag: string) {
        if(this.pos + len > this.data.length) len = this.data.length - this.pos;
        let tempBuffer: Buffer = this.data.slice(this.pos, this.pos + len);
        let tempString: string = "";
        for (let index = 0; index < len && index < tempBuffer.length; index++) {
            tempString = tempString + tempBuffer[index].toString();
        }
        console.log(tag + " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        console.log(tempString);
        console.log(tag + " <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");

    };
    public setPosition(pos: number) {
        if (pos < 0) pos = 0;
        if (pos > this.data.length) pos = this.data.length;
        this.pos = pos;
    }
    public getPosition():number{
        return this.pos;
    }
    public U(len: number): number {
        let ret: number = 0;
        // this.printNextBinary(len, "U");
        if (this.pos + len < this.data.length) {
            for (let index = 0; index < len; index++) {
                let value = this.data[this.pos];
                ret = (ret << 1) + value;
                this.pos++;
            }

        }
        return ret;
    }
    public UE(): number {
        let ret: number = 0;
        let len: number = 0;

        while (this.pos + len < this.data.length) {
            if (this.data[this.pos + len] === 0) {
                len++;
            } else {
                break;
            }
        }
        if (this.pos + len != this.data.length) {
            ret = this.U(len * 2 + 1) - 1;
        }
        return ret;
    }
    public SE(): number {//TODO 未实现功能,计划:根据大小判断数字节数，放buffer里去取有符号整形
        let ret: number = 0;
        let len: number = 0;
        while (this.pos + len < this.data.length) {
            if (this.data[this.pos + len] === 0) {
                len++;
            } else {
                break;
            }
        }
        if (this.pos + len != this.data.length) {
            ret = this.U(len * 2 + 1) - 1;
        }
        return ret;
    }
    private getValueBuffer(value: number): Buffer {
        let ret: Buffer = Buffer.alloc(8);
        for (let index = 0; index < ret.length; index++) {
            let temp: number = value;
            ret[index] = temp >> (7 - index) & 0x01;
        }
        return ret;
    }
    private initData(srcData: Buffer): void {
        for (let index = 0; index < srcData.length; index++) {
            let value: number = srcData[index];
            this.data = Buffer.concat(
                [
                    this.data,
                    this.getValueBuffer(value)
                ]
            );
        }
    };
}